const appointmentApi = require('../../api/appointment')
const packageApi = require('../../api/package')
const networkHelper = require('../../utils/network-helper')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 预约模式：by-date（按日期）或 by-hairdresser（按发型师）
    appointmentMode: 'by-date',
    
    // 理发师列表
    hairdresserList: [],
    selectedHairdresser: {},
    
    // 按日期模式的数据
    availableManagersByDate: [], // 指定日期可用的发型师
    
    // 按发型师模式的数据
    allStoreManagers: [], // 所有发型师
    managerAvailableDates: {}, // 发型师的可用日期
    managerDateList: [], // 发型师可用日期的数组格式（用于WXML渲染）
    
    // 时间相关
    availableDates: [],
    selectedDate: '',
    timeSlots: [],
    selectedTime: '',
    timeSlotAvailability: {}, // 时间段可用性缓存
    
    // 加载状态
    loading: false,
    loadingTimeSlots: false,
    loadingManagersByDate: false,
    loadingManagerDates: false,
    
    // 网络诊断
    showNetworkDiagnostic: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadAllStoreManagers()
    this.autoSelectTodayDate()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时清空之前的选择状态，重新开始选择
    this.setData({
      selectedHairdresser: {},
      selectedTime: '',
      timeSlots: []
    })
  },

  /**
   * 加载所有发型师数据
   */
  async loadAllStoreManagers() {
    try {
      wx.showLoading({ title: '加载发型师...' })
      const schedules = await appointmentApi.getAllStoreManagerSchedules()
      
      // 处理理发师数据
      const hairdresserList = schedules.map(item => ({
        storeManagerId: item.storeManagerId,
        storeManagerName: item.storeManagerName,
        avatar: item.avatar || '/images/default-avatar.png',
        level: '高级理发师',
        description: item.description || '经验丰富，技艺精湛',
        totalSchedules: item.totalSchedules || 0
      }))
      
      this.setData({
        hairdresserList,
        allStoreManagers: hairdresserList
      })
      
      wx.hideLoading()
    } catch (error) {
      console.error('加载理发师列表失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '加载理发师列表失败',
        icon: 'none'
      })
    }
  },

  /**
   * 预约模式切换
   */
  onModeChange(e) {
    const mode = e.detail.value
    this.setData({
      appointmentMode: mode,
      selectedHairdresser: {},
      selectedDate: '',
      selectedTime: '',
      availableManagersByDate: [],
      managerAvailableDates: {},
      timeSlots: []
    })
    
    // 如果切换到按日期模式，自动选择当天日期
    if (mode === 'by-date') {
      this.autoSelectTodayDate()
    }
  },

  /**
   * 自动选择当天日期
   */
  autoSelectTodayDate() {
    const today = new Date()
    const todayStr = today.getFullYear() + '-' + 
      String(today.getMonth() + 1).padStart(2, '0') + '-' + 
      String(today.getDate()).padStart(2, '0')
    
    this.setData({
      selectedDate: todayStr
    })
    
    // 生成可选日期列表
    this.generateAvailableDates()
    
    // 如果是按日期模式，自动加载当天的发型师
    if (this.data.appointmentMode === 'by-date') {
      this.onDateSelect(todayStr)
    }
  },

  /**
   * 按日期模式 - 日期选择
   */
  async onDateSelect(date) {
    if (!date) return
    
    console.log('=== onDateSelect 开始 ===', date)
    
    this.setData({
      selectedDate: date,
      selectedHairdresser: {},
      selectedTime: '',
      availableManagersByDate: [],
      timeSlots: [],
      loadingManagersByDate: true
    })
    
    try {
      console.log('正在获取日期的可用发型师:', date)
      const response = await appointmentApi.getAvailableStoreManagersByDate(date)
      console.log('获取发型师响应:', response)
      
      if (response && response.length >= 0) {
        const managers = response || []
        console.log('获取到的发型师数量:', managers.length)
        
        // 为每个发型师加载时间段可用性信息并添加到发型师数据中
        for (const manager of managers) {
          console.log(`开始为发型师 ${manager.storeManagerId} 加载时间段...`)
          const timeSlots = await this.loadTimeSlotAvailabilityForManager(manager.storeManagerId, date)
          manager.timeSlots = timeSlots || []
          console.log(`发型师 ${manager.storeManagerId} 的时间段:`, manager.timeSlots)
          
          // 验证时间段数据结构
          if (manager.timeSlots.length > 0) {
            manager.timeSlots.forEach((slot, index) => {
              if (typeof slot.available === 'undefined') {
                console.warn(`发型师 ${manager.storeManagerId} 时间段 ${index} 缺少available属性:`, slot)
                slot.available = (slot.remainingSlots || 0) > 0
              }
            })
          }
        }
        
        console.log('所有发型师时间段加载完成，设置数据...')
        
        this.setData({
          availableManagersByDate: managers,
          loadingManagersByDate: false
        })
        
        console.log('设置完成的availableManagersByDate:', this.data.availableManagersByDate)
        
        if (managers.length === 0) {
          wx.showToast({
            title: '该日期暂无可用发型师',
            icon: 'none'
          })
        }
      } else {
        throw new Error('响应数据格式错误')
      }
    } catch (error) {
      console.error('获取发型师失败:', error)
      
      this.setData({
        loadingManagersByDate: false,
        availableManagersByDate: []
      })
      
      let errorMessage = '获取发型师失败'
      if (error.message) {
        if (error.message.includes('网络')) {
          errorMessage = '网络连接失败，请检查网络设置'
        } else if (error.message.includes('登录')) {
          errorMessage = '登录已过期，请重新登录'
        } else {
          errorMessage = error.message
        }
      }
      
      wx.showModal({
        title: '获取发型师失败',
        content: errorMessage + '\n\n是否重试？',
        showCancel: true,
        confirmText: '重试',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.onDateSelect(date)
          }
        }
      })
    }
  },

  /**
   * 为发型师加载时间段可用性信息
   */
  async loadTimeSlotAvailabilityForManager(managerId, date) {
    try {
      console.log(`正在加载发型师${managerId}在${date}的时间段...`)
      const response = await appointmentApi.getStoreManagerTimeSlotAvailability(managerId, date)
      console.log(`发型师${managerId}在${date}的时间段原始响应:`, response)
      
      // response 现在直接是 data 部分（Array）
      if (response && Array.isArray(response)) {
        const timeSlots = response.map(slot => {
          // 确保available属性正确计算
          const remainingSlots = slot.remainingSlots || 0
          const available = remainingSlots > 0
          
          const processedSlot = {
            hour: slot.hour,
            timeRange: slot.timeRange || `${slot.hour}:00-${slot.hour + 1}:00`,
            available: available,
            remainingSlots: remainingSlots,
            maxAppointments: slot.maxAppointments || 1,
            bookedCount: slot.bookedCount || 0
          }
          
          console.log(`时间段 ${slot.hour} 处理结果:`, processedSlot)
          return processedSlot
        })
        console.log(`发型师${managerId}在${date}的处理后时间段:`, timeSlots)
        return timeSlots
      } else {
        console.warn(`发型师${managerId}在${date}的时间段数据格式错误:`, response)
        // 返回空数组而不是抛出错误，让页面继续正常工作
        return []
      }
    } catch (error) {
      console.error(`获取发型师${managerId}在${date}的时间段失败:`, error)
      // 返回空数组，确保不会阻塞其他功能
      return []
    }
  },

  /**
   * 按日期模式 - 选择发型师
   */
  selectManagerFromDate(e) {
    const manager = e.currentTarget.dataset.manager
    this.setData({
      selectedHairdresser: {
        id: manager.storeManagerId,
        name: manager.storeManagerName,
        avatar: manager.avatar
      },
      selectedTime: '' // 重置时间选择
    })
  },

  /**
   * 按日期模式 - 直接选择发型师和时间
   */
  selectDateTimeFromManager(e) {
    // 阻止事件冒泡
    e.stopPropagation && e.stopPropagation()
    
    const { manager, slot } = e.currentTarget.dataset
    
    console.log('=== selectDateTimeFromManager 被调用 ===')
    console.log('manager:', manager)
    console.log('slot:', slot)
    console.log('slot.available:', slot.available)
    console.log('slot.remainingSlots:', slot.remainingSlots)
    
    // 检查slot是否有有效数据
    if (!slot) {
      console.error('slot数据为空')
      wx.showToast({
        title: '时间段数据异常',
        icon: 'none'
      })
      return
    }
    
    // 检查时间段是否可用
    if (!slot.available || slot.remainingSlots <= 0) {
      console.log('时间段不可用，available:', slot.available, 'remainingSlots:', slot.remainingSlots)
      wx.showToast({
        title: '该时间段已满，请选择其他时间',
        icon: 'none'
      })
      return
    }
    
    console.log('选择时间段成功，准备跳转到套餐选择页面...')
    
    // 构建预约信息
    const appointmentInfo = {
      storeManagerId: manager.storeManagerId,
      storeManagerName: manager.storeManagerName,
      selectedDate: this.data.selectedDate,
      selectedTime: slot.hour,
      timeRange: slot.timeRange
    }
    
    console.log('预约信息:', appointmentInfo)
    
    // 跳转到套餐选择页面
    wx.navigateTo({
      url: `/pages/appointment-package/appointment-package?appointmentInfo=${encodeURIComponent(JSON.stringify(appointmentInfo))}`
    })
  },

  /**
   * 按发型师模式 - 选择发型师
   */
  async selectManagerForDates(e) {
    const manager = e.currentTarget.dataset.manager
    
    this.setData({
      selectedHairdresser: {
        id: manager.storeManagerId,
        name: manager.storeManagerName,
        avatar: manager.avatar
      },
      selectedDate: '',
      selectedTime: '',
      managerAvailableDates: {},
      managerDateList: [],
      timeSlots: [],
      loadingManagerDates: true
    })
    
    try {
      console.log('正在获取理发师可用日期:', manager.storeManagerId)
      
      // 先测试网络连接
      const networkStatus = await this.checkNetworkStatus()
      if (!networkStatus) {
        throw new Error('网络连接异常，请检查网络设置')
      }
      
      const response = await appointmentApi.getStoreManagerAvailableDates(manager.storeManagerId, 14)
      console.log('获取理发师可用日期响应:', response)
      
      // response 现在直接是 data 部分（Map 对象）
      if (response && typeof response === 'object') {
        const availableDates = response || {}
        console.log('可用日期数据:', availableDates)
        
        // 为每个日期加载时间段可用性信息
        const dateKeys = Object.keys(availableDates)
        if (dateKeys.length > 0) {
          for (const date of dateKeys) {
            try {
              await this.loadTimeSlotAvailability(manager.storeManagerId, date)
            } catch (timeSlotError) {
              console.warn(`加载日期${date}的时间段失败:`, timeSlotError)
              // 继续处理其他日期，不中断整个流程
            }
          }
        }
        
        // 转换为数组格式，方便WXML渲染
        const dateList = dateKeys.map(date => {
          const hours = availableDates[date] || []
          const managerId = manager.storeManagerId
          const key = `${managerId}_${date}`
          
          // 获取时间段可用性数据
          let timeSlots = this.data.timeSlotAvailability[key] || []
          
          // 如果没有时间段数据，基于小时数组生成基础时间段
          if (timeSlots.length === 0 && hours.length > 0) {
            timeSlots = hours.map(hour => ({
              hour,
              timeRange: `${hour}:00-${hour + 1}:00`,
              maxAppointments: 1,
              bookedCount: 0,
              remainingSlots: 1,
              available: true
            }))
          }
          
          console.log(`日期 ${date} 的时间段数据:`, timeSlots)
          
          return {
            date,
            hours,
            timeSlots // 直接包含处理好的时间段数据
          }
        })
        
        console.log('转换后的dateList:', dateList)
        
        this.setData({
          managerAvailableDates: availableDates,
          managerDateList: dateList, // 新增数组格式用于WXML渲染
          loadingManagerDates: false
        })
        
        console.log('设置后的managerAvailableDates:', this.data.managerAvailableDates)
        console.log('设置后的managerDateList:', this.data.managerDateList)
        console.log('Object.keys(managerAvailableDates):', Object.keys(this.data.managerAvailableDates))
        
        if (dateKeys.length === 0) {
          wx.showToast({
            title: '该理发师近期暂无可用时间',
            icon: 'none',
            duration: 2000
          })
        }
      } else {
        console.error('获取可用日期数据格式异常:', response)
        throw new Error('数据格式异常')
      }
    } catch (error) {
      console.error('获取可用日期失败:', error)
      
      this.setData({
        loadingManagerDates: false,
        managerAvailableDates: {}
      })
      
      // 显示详细的错误信息
      let errorMessage = '获取时间表失败'
      
      if (error.message) {
        if (error.message.includes('网络')) {
          errorMessage = '网络连接失败，请检查网络设置'
        } else if (error.message.includes('登录')) {
          errorMessage = '登录已过期，请重新登录'
        } else if (error.message.includes('权限')) {
          errorMessage = '没有访问权限'
        } else {
          errorMessage = error.message
        }
      }
      
      wx.showModal({
        title: '获取时间表失败',
        content: errorMessage + '\n\n是否重试？',
        showCancel: true,
        confirmText: '重试',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 用户选择重试
            this.selectManagerForDates(e)
          }
        }
      })
    }
  },

  /**
   * 检查网络状态
   */
  async checkNetworkStatus() {
    return new Promise((resolve) => {
      wx.getNetworkType({
        success: (res) => {
          console.log('网络类型:', res.networkType)
          if (res.networkType === 'none') {
            resolve(false)
          } else {
            resolve(true)
          }
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  },

  /**
   * 按发型师模式 - 选择日期和时间
   */
  selectDateTimeSlot(e) {
    // 阻止事件冒泡
    e.stopPropagation && e.stopPropagation()
    
    const { date, slot } = e.currentTarget.dataset
    
    console.log('=== selectDateTimeSlot 被调用 ===')
    console.log('date:', date)
    console.log('slot:', slot)
    console.log('slot.available:', slot.available)
    console.log('slot.remainingSlots:', slot.remainingSlots)
    
    // 检查slot是否有有效数据
    if (!slot) {
      console.error('slot数据为空')
      wx.showToast({
        title: '时间段数据异常',
        icon: 'none'
      })
      return
    }
    
    // 检查时间段是否可用
    if (!slot.available || slot.remainingSlots <= 0) {
      console.log('时间段不可用，available:', slot.available, 'remainingSlots:', slot.remainingSlots)
      wx.showToast({
        title: '该时间段已满，请选择其他时间',
        icon: 'none'
      })
      return
    }
    
    console.log('选择日期时间段成功，准备跳转到套餐选择页面...')
    
    // 构建预约信息
    const appointmentInfo = {
      storeManagerId: this.data.selectedHairdresser.id,
      storeManagerName: this.data.selectedHairdresser.name,
      selectedDate: date,
      selectedTime: slot.hour,
      timeRange: slot.timeRange
    }
    
    console.log('预约信息:', appointmentInfo)
    
    // 跳转到套餐选择页面
    wx.navigateTo({
      url: `/pages/appointment-package/appointment-package?appointmentInfo=${encodeURIComponent(JSON.stringify(appointmentInfo))}`
    })
  },

  /**
   * 获取发型师时间段可用性信息
   */
  getManagerTimeSlots(manager) {
    const key = `${manager.storeManagerId}_${this.data.selectedDate}`
    return this.data.timeSlotAvailability[key] || []
  },

  /**
   * 生成可选日期列表（未来7天）
   */
  generateAvailableDates() {
    const dates = []
    const today = new Date()
    const weekDays = ['日', '一', '二', '三', '四', '五', '六']
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    
    for (let i = 0; i < 7; i++) {
      const date = new Date(today.getTime() + i * 24 * 60 * 60 * 1000)
      const dateStr = this.formatDateToString(date)
      
      dates.push({
        date: dateStr,
        day: date.getDate(),
        month: months[date.getMonth()],
        week: weekDays[date.getDay()]
      })
    }
    
    this.setData({
      availableDates: dates
    })
  },

  /**
   * 格式化日期为 YYYY-MM-DD 字符串
   */
  formatDateToString(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  /**
   * 获取日期时间段可用性信息
   */
  getDateTimeSlots(date, hours) {
    console.log(`=== getDateTimeSlots 被调用 ===`)
    console.log(`参数 - date: ${date}`)
    console.log(`参数 - hours:`, hours)
    console.log(`当前selectedHairdresser.id: ${this.data.selectedHairdresser.id}`)
    
    const key = `${this.data.selectedHairdresser.id}_${date}`
    const slots = this.data.timeSlotAvailability[key] || []
    
    console.log(`获取时间段 ${key}:`, slots)
    console.log(`可用小时:`, hours)
    
    // 如果有时间段可用性数据，直接返回
    if (slots.length > 0) {
      console.log(`返回时间段数据:`, slots)
      return slots
    }
    
    // 如果没有可用性数据，且有小时数组，基于小时数组生成基础时间段信息
    if (hours && Array.isArray(hours) && hours.length > 0) {
      const basicSlots = hours.map(hour => ({
        hour,
        timeRange: `${hour}:00-${hour + 1}:00`,
        maxAppointments: 1,
        bookedCount: 0,
        remainingSlots: 1,
        available: true
      }))
      console.log(`生成基础时间段:`, basicSlots)
      return basicSlots
    }
    
    console.log(`无时间段数据返回空数组`)
    return []
  },

  /**
   * 加载时间段可用性信息
   */
  async loadTimeSlotAvailability(managerId, date) {
    try {
      const key = `${managerId}_${date}`
      if (this.data.timeSlotAvailability[key]) {
        console.log(`时间段数据已缓存: ${key}`)
        return // 已经加载过了
      }
      
      console.log(`正在加载时间段可用性: ${key}`)
      const response = await appointmentApi.getStoreManagerTimeSlotAvailability(managerId, date)
      console.log(`时间段可用性响应:`, response)
      
      // response 现在直接是 data 部分（Array）
      if (response && Array.isArray(response)) {
        const availability = { ...this.data.timeSlotAvailability }
        availability[key] = response || []
        this.setData({
          timeSlotAvailability: availability
        })
        console.log(`时间段数据已更新: ${key}`, availability[key])
      } else {
        console.warn(`时间段可用性数据异常:`, response)
        // 即使失败也要设置空数组，避免重复请求
        const availability = { ...this.data.timeSlotAvailability }
        availability[key] = []
        this.setData({
          timeSlotAvailability: availability
        })
      }
    } catch (error) {
      console.error('获取时间段可用性失败:', error)
      // 设置空数组，避免重复请求同一个接口
      const key = `${managerId}_${date}`
      const availability = { ...this.data.timeSlotAvailability }
      availability[key] = []
      this.setData({
        timeSlotAvailability: availability
      })
    }
  },

  /**
   * 选择日期
   */
  selectDate(e) {
    const selectedDate = e.currentTarget.dataset.date
    
    if (this.data.appointmentMode === 'by-date') {
      this.onDateSelect(selectedDate)
    } else {
      this.setData({
        selectedDate,
        selectedTime: ''
      })
    }
  },

  /**
   * 选择时间
   */
  selectTime(e) {
    const time = e.currentTarget.dataset.time
    const timeSlot = this.data.timeSlots.find(slot => slot.hour === time)
    
    if (timeSlot && timeSlot.available) {
      this.setData({
        selectedTime: time
      })
    } else {
      wx.showToast({
        title: '该时间段已满，请选择其他时间',
        icon: 'none'
      })
    }
  },

  /**
   * 备注输入
   */
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  /**
   * 重置表单
   */
  resetForm() {
    this.setData({
      selectedHairdresser: {},
      selectedDate: '',
      selectedTime: '',
      managerAvailableDates: {},
      managerDateList: [],
      timeSlots: [],
      timeSlotAvailability: {}
    })
    this.autoSelectTodayDate()
  },

  /**
   * 格式化日期显示
   */
  formatSelectedDate() {
    if (this.data.selectedDate) {
      const date = new Date(this.data.selectedDate)
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${month}月${day}日`
    }
    return '选择日期'
  },

  /**
   * 格式化日期
   */
  formatDate(dateStr) {
    const date = new Date(dateStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}月${day}日`
  },

  /**
   * 获取星期几
   */
  getWeekday(dateStr) {
    const date = new Date(dateStr)
    const weekDays = ['日', '一', '二', '三', '四', '五', '六']
    return `周${weekDays[date.getDay()]}`
  },

  /**
   * 显示网络诊断
   */
  async showNetworkDiagnostic() {
    const app = getApp()
    
    wx.showModal({
      title: '网络诊断信息',
      content: `API地址: ${app.globalData.baseUrl}\n当前时间: ${new Date().toLocaleString()}\n请检查:\n1. 后端服务是否启动\n2. 网络连接是否正常\n3. 防火墙设置`,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 测试网络连接
   */
  async testNetworkConnection() {
    wx.showLoading({
      title: '测试连接中...'
    })
    
    try {
      // 测试基础连接
      const networkStatus = await this.checkNetworkStatus()
      if (!networkStatus) {
        throw new Error('网络不可用')
      }
      
      // 测试API连接
      const testResponse = await appointmentApi.getAllStoreManagerSchedules()
      console.log('网络测试响应:', testResponse)
      
      wx.hideLoading()
      
      if (testResponse && Array.isArray(testResponse)) {
        wx.showModal({
          title: '网络连接正常',
          content: `成功获取到 ${testResponse.length} 个理发师的数据\n\nAPI响应正常，如果仍有问题，请检查:\n1. 理发师是否设置了排班\n2. 数据库数据是否完整`,
          showCancel: false,
          confirmText: '知道了'
        })
      } else {
        wx.showModal({
          title: '数据异常',
          content: 'API连接正常但数据格式异常，请检查后端服务',
          showCancel: false,
          confirmText: '知道了'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('网络测试失败:', error)
      
      const app = getApp()
      wx.showModal({
        title: '网络连接失败',
        content: `错误信息: ${error.message}\n\nAPI地址: ${app.globalData.baseUrl}\n\n请检查:\n1. 后端服务是否启动\n2. 网络设置是否正确\n3. 防火墙是否阻挡连接`,
        showCancel: true,
        confirmText: '重新测试',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.testNetworkConnection()
          }
        }
      })
    }
  },

  /**
   * 测试方法 - 获取特定日期的时间段（供WXML直接调用）
   */
  getTestTimeSlots(date, hours) {
    console.log(`=== getTestTimeSlots 被调用 ===`)
    console.log(`日期: ${date}, 小时数组:`, hours)
    
    // 直接返回基础时间段用于测试
    if (hours && hours.length > 0) {
      const testSlots = hours.slice(0, 3).map(hour => ({
        hour,
        timeRange: `${hour}:00-${hour + 1}:00`,
        maxAppointments: 2,
        bookedCount: 0,
        remainingSlots: 2,
        available: true
      }))
      console.log(`测试返回时间段:`, testSlots)
      return testSlots
    }
    return []
  },
}) 